package com.rn.ddd.application.service.impl;

import com.rn.ddd.application.service.MerchantService;
import com.rn.ddd.domain.merchant.entity.Merchant;
import com.rn.ddd.domain.merchant.repository.MerchantRepository;
import com.rn.ddd.domain.merchant.service.MerchantDomainService;
import com.rn.gypsophila.ex.BizException;
import com.rn.gypsophila.ex.GlobalExCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商户应用服务实现
 *
 * @author 然诺
 * @date 2021/8/15
 */
@Service
public class MerchantServiceImpl implements MerchantService {

    @Autowired
    private MerchantDomainService merchantDomainService;
    @Autowired
    private MerchantRepository merchantRepository;

    @Override
    public Merchant getMerchant(Long merchantId) {
        return merchantDomainService.getById(merchantId);
    }

    @Override
    public boolean checkMerchantName(String merchantName, Long... exclude) {
        return merchantRepository.checkMerchantName(merchantName, exclude) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void registerMerchant(Merchant merchant) {
        // 1. 检查商户用户名是否合法
        if (checkMerchantName(merchant.getMerchantName())) {
            throw new BizException("商户名已经存在,请重新输入");
        }
        // 2. 数据持久化
        boolean saveOrUpdate = merchantRepository.saveOrUpdate(merchant);
        if (!saveOrUpdate) {
            throw new BizException(GlobalExCode.ACTION_FAILURE);
        }
    }

}
